<template>
  <div class="history_chat_list left">
    <transition>
      <div class="left-title" v-if="props.isCollapse">
        <span>对话历史</span>
        <img src="@/assets/agent/chat/shouqi.svg" alt="" @click="handelCollapse" />
      </div>
      <img
        v-else
        class="top-icon"
        src="@/assets/agent/chat/shouqi.svg"
        alt=""
        @click="handelCollapse"
      />
    </transition>
    <div class="flex-1">
      <div class="left-content">
        <div class="text-center" v-if="recordList.length === 0 && props.isCollapse">
          <el-text type="info">历史对话</el-text>
        </div>
        <div
          v-for="(v, i) in recordList"
          :class="{ 'left-content-item': true, active: `${chatId}` === `${(v as any).chatId}` }"
          :key="i"
          @click="clickListHandle(v)"
        >
          <!-- @mouseenter.stop="showMoreId = (v as any).id" -->
          <img class="left-content-item-left" :src="defImg" alt="img" />
          <transition>
            <div class="left-content-item-right" v-if="isCollapse">
              <div class="left-content-item-right-title">
                {{ v.lastQuestion === 'Hello, welcome to using supersonic'?  v.chatName : v.lastQuestion }}
              </div>
              <div class="left-content-item-right-time">
                {{ dayjs(v.lastTime).format('HH:mm:ss') }}
              </div>
            </div>
          </transition>
          <transition @click.stop>
            <el-dropdown v-if="isCollapse && v.id !== 'new'" trigger="hover">
              <div class="left-content-item-more" @click.stop>
                <img src="@/assets/agent/chat/more.svg" alt="" />
              </div>
              <template #dropdown>
                <el-dropdown-menu :teleported="false">
                  <el-dropdown-item @click="deleteLog(v)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </transition>
        </div>
      </div>
    </div>
    <div
      class="left-add"
      :style="{ border: isCollapse ? '1px solid rgba(48,103,239,0.6)' : 'none' }"
    >
      <el-button
        class="button"
        v-if="isCollapse"
        :icon="Plus"
        round
        style="width: 100%"
        @click="webappChatOpen"
        >新建会话</el-button
      >
      <el-icon v-else :size="32" color="#3067EF" style="cursor: pointer"  @click="webappChatOpen">
        <CirclePlus/>
      </el-icon>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, onBeforeUnmount } from 'vue'
import dayjs from 'dayjs'
import defImg from '@/assets/agent/def_agent.svg'
import { CirclePlus, Plus } from '@element-plus/icons-vue'
import ChatBi from '@/api/chatbi'
import useStore from '@/stores'
import bus from '@/bus'

const { chatbi } = useStore()

const props = defineProps<{
  agentId: any /** 对话智能体id */
  isCollapse: boolean /* 是否折叠 */
}>()

const emit = defineEmits(['handelItem', 'handelDelItem', 'handelCollapse'])

const recordList = ref<any>([]);
const chatId = ref('');
const pageLoadding = ref(false); /** 分页loadding */
const isMore = ref(true); /** 是否还有更多数据 */
const pageConfig = ref<any>({
  current: 1,
  pageSize: 3
})

function webappChatOpen() {
  bus.emit('webapp-chat-open')
}

/** 展开收起 */
function handelCollapse() {
    emit('handelCollapse', !props.isCollapse)
}

/** 对话记录切换 */
function clickListHandle(item: any){
    chatbi.setChatList([],true, true)
    localStorage.setItem('chatId', item.chatId)
    chatId.value = item.chatId
    emit('handelItem', item)
}

/** 删除对话记录 */
function deleteLog(item: any) {
  
    if(recordList.value.length < 2) return
    const localChatId = localStorage.getItem('chatId');
    if (`${localChatId}` === `${item.chatId}`) {
        chatbi.setChatList([],true, true)
    }
    emit('handelDelItem', item)
    ChatBi.deleteChat({ chatId: item.chatId })
        .then((res:any) => {
            console.log(res);
            getAllChat(item.agentId);
        }).catch((err) => {
            console.log(err);
        })
}

/**
 * 根据 agentId 获取对话历史列表
 * @param id agentId
 */
 function getAllChat(id: string) {
  if (!id) return 
  ChatBi.getChatList(id).then((res) => {
    if (res.data && res.data.length) {
        const tempChatid = localStorage.getItem('chatId');
        let activeChatId = tempChatid ? tempChatid : res.data[0].chatId
        if(!res.data.some((el: any)=> `${el.chatId}` === `${activeChatId}`)) {
           activeChatId = res.data[0].chatId
        }
        localStorage.setItem('chatId', activeChatId)
        chatId.value = activeChatId
        recordList.value = res.data
    } else if (res.data && res.data.length === 0) {
      ChatBi.saveChat({agentId: id, chatName: '新问答对话'})
        .then((res: any) => {
          console.log(res)
          getAllChat(id)
        })
        .catch((err: any) => {
          console.log(err)
        }).finally
    }
  })
}

/** 根据chatId获取对话记录 */
function getPageChatInfo(chatId: any, isPush = true) {
  pageLoadding.value = true
  ChatBi.pageQueryInfo(chatId, { ...pageConfig.value })
    .then((res: any) => {
      if(res.data && res.data.list.length) {
        chatbi.setChatList(res.data.list, isPush)
      }
      /* 判断是否到底了 */ 
      if(res.data && res.data.pages <= pageConfig.value.current) {
        isMore.value = false
      }
    })
    .catch((err: any) => {
      console.log(err)
    }).finally( ()=> {
      setTimeout(()=> {
        pageLoadding.value = false
      },300)
    })
}

function scrollTopLoadPage() {
  if(!pageLoadding.value && isMore.value){
      console.log('[ bus scrollToTop 加载顶部数据... ]')
      pageConfig.value.current =  pageConfig.value.current + 1
      getPageChatInfo(chatId.value,  false)
  }
}

/** 监听chatId的变化 */
watch(() => chatId.value, (newVal: any, oldVal: any) => {
    if (newVal && newVal !== oldVal) {
      console.log('[ 对话历史发生改变 ]', newVal)
      pageConfig.value.current = 1
      pageConfig.value.pageSize = 3
      isMore.value = true
      getPageChatInfo(newVal)
      /*  通知chatid 更新了*/
      bus.emit('bus-chatid-update',chatId.value)
    }
    
}, { immediate: true, deep: true })

/** 监听agentId的变化 */
watch(() => props.agentId, (newVal: any) => {
    if (newVal) {
        getAllChat(newVal);
    }
}, { immediate: true })

onMounted(() => {
  bus.on('scrollToTop', scrollTopLoadPage)
})

onBeforeUnmount(()=> {
  bus.off('scrollToTop', scrollTopLoadPage)
})


</script>

<style lang="scss" scoped>

</style>
